<template>
  <div>
    <el-form
      ref="queryForm"
      :model="queryParams"
      :inline="true"
    >
      <el-form-item :label="$t('staff.search')" prop="type">
        <el-select
          v-model="queryParams.type"
          placeholder="请选择"
          @change="changeQuery"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <!-- <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
        >{{ $t("operating.search") }}</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{
          $t("operating.reset")
        }}</el-button>-->
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:post:add']"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >{{ $t('common.caddkey') }}</el-button>
      </el-col>

      <!-- <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:post:remove']"
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleBitchDelete"
        >{{ $t('common.cdelete') }}</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:post:export']"
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >{{ $t("operating.export") }}</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleExport"
        >{{ $t("operating.import") }}</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:post:export']"
          type="info"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handledownloadExp"
        >{{ $t("staff.downloadExp") }}</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:post:updateOrder']"
          type="info"
          plain
          icon="el-icon-edit"
          size="mini"
          @click="updateOrder()"
        >{{ $t("common.cupdateOrder") }}</el-button>
      </el-col> -->
    </el-row>
    <el-table :data="fenceData" border align="left" row-key="id">
      <!--  @selection-change="handleSelectionChange"
      <el-table-column type="selection" min-width="50" align="center" /> -->

      <el-table-column
        v-for="(item, index) in col"
        :key="`col_${index}`"
        :prop="dropCol[index].prop"
        :label="item.label"
      />
      <el-table-column :label="$t('common.coperation')" width="100">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            @click="handleEdit(scope.row)"
          >{{ $t('common.cupdate') }}</el-button>
          <el-button
            type="text"
            size="small"
            @click="handleDelete(scope.row)"
          >{{ $t('common.cdelete') }}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="initData"
    />

    <el-dialog
      title="添加"
      :visible.sync="dialogVisible"
      width="20%"
      :before-close="handleClose"
    >
      <div class="flowForms">
        <div>
          <el-tooltip
            class="item"
            effect="dark"
            :content="$t('common.cmore')"
            placement="top-start"
          >
            <i class="iconfont iconadd" @click="moreDetail()" />
          </el-tooltip>
          <!-- <i class="iconfont iconadd" /> -->
        </div>
        <el-form
          ref="formFlow"
          :model="formFlow"
          :rules="rules"
          :inline="true"
          label-width="80px"
        >
          <el-form-item label="流程名称" prop="type">
            <el-select
              v-model="formFlow.type"
              placeholder="请选择"
              @change="changeQuery"
            >
              <el-option
                v-for="item in optionlist"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select> </el-form-item><br>
          <el-form-item :label="$t('ccworkflow.operationName')" prop="operationName">
            <el-input
              v-model="formFlow.operationName"
              width="100%"
            /> </el-form-item><br>

          <el-form-item :label="$t('ccworkflow.mapId')" prop="mapId">
            <treeselect
              v-model="formFlow.mapId"
              :placeholder="$t('area.chosenLayer')"
              :max-height="300"
              :options="mapList"
              style="float: left; width: 200px"
              @input="nodeClick"
            /> </el-form-item><br>

          <el-form-item
            v-show="fenceList.length > 0"
            label="绑定围栏"
            prop="fenceId"
          >
            <el-select
              v-model="formFlow.fenceId"
              placeholder="请选择"
              @change="changeQFence"
            >
              <el-option
                v-for="item in fenceList"
                :key="item.id + item.properties.id"
                :label="item.properties.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <div v-show="isMore">
            <el-form-item :label="$t('ccworkflow.orderNum')" prop="orderNum">
              <el-input-number
                v-model="formFlow.orderNum"
                controls-position="right"
                :min="1"
                :max="10"
              />
            </el-form-item>
            <el-form-item :label="$t('ccworkflow.maxDuration')" prop="maxDuration">
              <el-input v-model="formFlow.maxDuration" />
            </el-form-item>
            <el-form-item :label="$t('ccworkflow.minDuration')" prop="minDuration">
              <el-input v-model="formFlow.minDuration" />
            </el-form-item>
            <el-form-item :label="$t('ccworkflow.intoCount')" prop="intoCount">
              <el-input v-model="formFlow.intoCount" />
            </el-form-item>
            <el-form-item :label="$t('ccworkflow.remark')" prop="remark">
              <el-input v-model="formFlow.remark" />
            </el-form-item>
          </div>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="addFlow()"
            >{{ $t("common.cadd") }}</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetFlow">{{
              $t("operating.reset")
            }}</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>

    <el-dialog
      title="修改"
      :visible.sync="isEdit"
      width="20%"
      :before-close="handleCloseEdit"
    >
      <div class="flowForms">
        <el-form
          ref="formFlowEdit"
          :model="formFlowEdit"
          :rules="rulesEdit"
          :inline="true"
          label-width="80px"
        >
          <el-form-item :label="$t('ccworkflow.type')" prop="type">
            <el-select
              v-model="formFlowEdit.type"
              placeholder="请选择"
              @change="changeQuery"
            >
              <el-option
                v-for="item in optionlist"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select> </el-form-item><br>

          <el-form-item :label="$t('ccworkflow.operationName')" prop="operationName">
            <el-input
              v-model="formFlowEdit.operationName"
              width="100%"
            /> </el-form-item><br>
          <!--
          <el-form-item label="围栏顺序" prop="orderNum">
            <el-input-number
              v-model="formFlowEdit.orderNum"
              controls-position="right"
              :min="1"
              :max="10"
            />
          </el-form-item> -->
          <el-form-item :label="$t('ccworkflow.maxDuration')" prop="maxDuration">
            <el-input v-model="formFlowEdit.maxDuration" />
          </el-form-item>

          <el-form-item :label="$t('ccworkflow.minDuration')" prop="minDuration">
            <el-input v-model="formFlowEdit.minDuration" />
          </el-form-item>

          <el-form-item :label="$t('ccworkflow.intoCount')" prop="intoCount">
            <el-input v-model="formFlowEdit.intoCount" />
          </el-form-item>

          <el-form-item :label="$t('ccworkflow.remark')" prop="remark">
            <el-input v-model="formFlowEdit.remark" />
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="editForm()"
            >{{ $t("common.cupdate") }}</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetFlowEdit">{{
              $t("operating.reset")
            }}</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import Sortable from 'sortablejs'
import Treeselect from '@riophae/vue-treeselect'
// import the styles
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import {
  ccFenceAdd,
  ccFenceEdit,
  ccFenceDelete,
  ccFenceList,
  ccFenceAllList,
  ccFenceSave,
  downloadFile,
  getAllFence,
  ccFencQOrderNum,
  ccfenceModify
} from '@/api/cy.js'
export default {
  components: {
    Treeselect
  },
  filters: {
    formatNoteType(value) {
      if (value === 1) {
        return '作业流程'
      } else {
        return '路测流程'
      }
    }
  },
  props: {
    mapList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      isEdit: false,
      isMore: false,
      dialogVisible: false,
      drag: false,
      total: 0,
      formFlowEdit: {
        type: '1', // 流程类形
        operationName: undefined, // 工序名称
        fenceId: '', // 绑定围栏id
        maxDuration: 0,
        minDuration: 0,
        intoCount: 0,
        orderNum: 1,
        fenceName: undefined,
        remark: undefined
      },
      rulesEdit: {},
      formFlow: {
        type: '1', // 流程类形
        operationName: undefined, // 工序名称
        mapId: undefined, // 图层选择
        fenceId: '', // 绑定围栏id
        maxDuration: 0,
        minDuration: 0,
        intoCount: 0,
        orderNum: 1,
        fenceName: undefined,
        remark: undefined
      },
      rules: {
        operationName: [
          { required: true, message: '工序名称不能为空', trigger: 'blur' }
        ],
        mapId: [{ required: true, message: '图层不能为空', trigger: 'blur' }],
        fenceId: [{ required: true, message: '围栏不能为空', trigger: 'blur' }]
      },
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type: 'all'
      },
      multiple: false,
      fenceList: [],
      optionlist: [
        {
          value: '1',
          label: '作业流程'
        },
        {
          value: '2',
          label: '路测流程'
        }
      ],
      options: [
        {
          value: 'all',
          label: '所有'
        },

        {
          value: '1',
          label: '作业流程'
        },
        {
          value: '2',
          label: '路测流程'
        }
      ],
      col: [
        {
          label: 'Id号',
          prop: 'operationId'
        },
        {
          label: this.$i18n.t('ccworkflow.operationName'),
          prop: 'operationName'
        },
        {
          label: this.$i18n.t('ccworkflow.type'),
          prop: 'workflow'
        },

        {
          label: '围栏Id',
          prop: 'fenceId'
        },

        {
          label: '围栏名',
          prop: 'fenceName'
        },
        {
          label: this.$i18n.t('ccworkflow.orderNum'),
          prop: 'orderNum'
        },
        {
          label: this.$i18n.t('ccworkflow.maxDuration'),
          prop: 'maxDuration'
        },
        {
          label: this.$i18n.t('ccworkflow.minDuration'),
          prop: 'minDuration'
        },
        {
          label: this.$i18n.t('ccworkflow.intoCount'),
          prop: 'intoCount'
        },
        {
          label: this.$i18n.t('ccworkflow.remark'),
          prop: 'remark'
        }
      ],
      dropCol: [
        {
          label: 'Id号',
          prop: 'operationId'
        },
        {
          label: '工序名称',
          prop: 'operationName'
        },
        {
          label: this.$i18n.t('ccworkflow.type'),
          prop: 'workflow'
        },

        {
          label: '围栏Id',
          prop: 'fenceId'
        },

        {
          label: '围栏名',
          prop: 'fenceName'
        },
        {
          label: '顺序',
          prop: 'orderNum'
        },
        {
          label: '最大时长',
          prop: 'maxDuration'
        },
        {
          label: '最小时长',
          prop: 'minDuration'
        },
        {
          label: '进入次数',
          prop: 'intoCount'
        },
        {
          label: '备注',
          prop: 'remark'
        }
      ],
      fenceData: []
    }
  },
  mounted() {
    // this.rowDrop()
    this.initData()
    // this.columnDrop()
  },
  methods: {
    editForm() {
      ccfenceModify(this.formFlowEdit).then((res) => {
        if (res.code === 200) {
          this.msgSuccess(res.msg)
          this.isEdit = false
          setTimeout(() => {
            this.initData()
          }, 1500)
        }
      })
    },

    handleEdit(row) {
      console.log(row)
      this.formFlowEdit = row
      this.isEdit = true
    },
    resetFlowEdit() {
      this.isEdit = false
    },

    handleCloseEdit() {
      // this.formFlow = {
      //   type: '1',
      //   operationName: undefined,
      //   mapId: undefined,
      //   fenceId: undefined,
      //   maxDuration: 0,
      //   minDuration: 0,
      //   intoCount: 0,
      //   orderNum: 1,
      //   fenceName: undefined,
      //   remark: undefined
      // }
      this.isEdit = false
    },

    // 显示更多
    moreDetail() {
      this.isMore = !this.isMore
    },
    nodeClick() {
      if (this.formFlow.mapId === '' || this.formFlow.mapId === undefined) {
        return
      }
      getAllFence(this.formFlow.mapId).then((res) => {
        if (res.code === 200) {
          this.fenceList = res.data
          this.formFlow.fenceId = undefined
        }
      })
    },
    addFlow() {
      this.$refs['formFlow'].validate((valid) => {
        if (valid) {
          this.formFlow.type = parseInt(this.formFlow.type)
          console.log(this.formFlow, this.formFlow.type)

          ccFenceAdd(this.formFlow).then((res) => {
            if (res.code === 200) {
              this.msgSuccess(res.msg)
              this.handleClose()
              this.initData()
            } else {
              this.msgError(res.msg)
              this.handleClose()
            }
          })
        }
      })
    },
    resetFlow() {
      this.handleClose()
      this.resetForm('formFlow')
      this.handleQuery()
    },

    handleClose() {
      this.formFlow = {
        type: '1',
        operationName: undefined,
        mapId: undefined,
        fenceId: undefined,
        maxDuration: 0,
        minDuration: 0,
        intoCount: 0,
        orderNum: 1,
        fenceName: undefined,
        remark: undefined
      }
      this.dialogVisible = false
    },
    changeQFence(e) {
      this.fenceList.map((item) => {
        if (item.id === e) {
          this.formFlow.fenceName = item.properties.name
        }
      })
    },
    changeQuery(e) {
      this.handleQuery()
    },
    // 更新排序
    updateOrder() {
      const newArrayOrder = JSON.parse(JSON.stringify(this.fenceData)).map(
        (item, index) => {
          item.orderNum = index + 1
          return item
        }
      )
      ccFenceAdd(newArrayOrder).then((res) => {
        if (res.code === 200) {
          this.msgSuccess(res.msg)
        }
      })
    },
    initData() {
      if (this.queryParams.type === 'all') {
        ccFenceAllList().then((res) => {
          if (res.code === 200) {
            res.data.map((item) => {
              if (item.type.toString() === '1') {
                item.workflow = '作业流程'
              } else {
                item.workflow = '路测流程'
              }
            })
            this.fenceData = res.data
            this.total = res.data.length
          }
        })
      } else {
        ccFenceList(this.queryParams).then((res) => {
          if (res.code === 200) {
            res.rows.map((item) => {
              if (item.type.toString() === '1') {
                item.workflow = '作业流程'
              } else {
                item.workflow = '路测流程'
              }
            })
            this.fenceData = res.rows
            this.total = res.total
          }
        })
      }
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      console.log('全选', selection)
    },

    // 开始拖拽事件
    onStart() {
      this.drag = true
    },
    // 拖拽结束事件
    onEnd() {
      this.drag = false
    },
    handledownloadExp() {},
    /** 导出按钮操作 */
    handleExport() {
      // 根据搜索条件导出内容
      const urlPath = '/socket/process/export'
      const filename = 'workflow_' + new Date().getTime() + '.xls'
      this.download(urlPath, {}, filename)
      // ccFencExport(urlPath, filename)
      // downloadFile(urlPath, filename)
      // ccFencExport(urlPath, {
      //   ...this.queryParams
      // }, filename)
    },
    handleAdd() {
      this.dialogVisible = true
      this.isMore = false
    },
    handleUpdate() {},

    /**
     * 批量删除
     */
    handleBitchDelete() {
      this.deleteData(this.$i18n.t('common.cdelTip'), this.ids)
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      this.deleteData(
        this.$i18n.t('common.cdelTipItem') + row.operationId,
        row.operationId
      )
    },

    deleteData(delTip, delData) {
      this.$confirm(delTip, this.$i18n.t('common.cwarn'), {
        confirmButtonText: this.$i18n.t('common.cok'),
        cancelButtonText: this.$i18n.t('common.ccancel'),
        type: 'warning'
      })
        .then(function() {
          return ccFenceDelete(delData)
        })
        .then((response) => {
          this.msgSuccess(response.msg)
          setTimeout(() => {
            this.initData()
          }, 1500)
        })
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.initData()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },

    // 行拖拽
    rowDrop() {
      const tbody = document.querySelector('.el-table__body-wrapper tbody')
      const that = this

      // 结束拖拽
      Sortable.create(tbody, {
        // 元素未被选中的时候（从选中到未选中）
        onUnchoose: function(evt) {
          console.log('未选中', evt)
          // same properties as onEnd
        },
        // 拖拽元素改变位置的时候
        onChange: function(/** Event*/ evt) {
          console.log('新元素', evt.newIndex)
        },
        onUpdate: function(evt) {
          console.log('列表内元素顺序更新', evt)
          // same properties as onEnd
        },
        onEnd(evt) {
          console.log('更新内功', evt.newIndex, evt.oldIndex)
          that.fenceData.splice(
            evt.newIndex,
            0,
            that.fenceData.splice(evt.oldIndex, 1)[0]
          )
          var newArray = that.fenceData.slice(0)
          that.fenceData = []
          that.$nextTick(function() {
            that.fenceData = newArray
          })
          console.log(that.fenceData)
        }
      })
    },

    handleClick(row) {
      console.log('row', row)
    }
    // // 列拖拽
    // columnDrop() {
    //   const wrapperTr = document.querySelector('.el-table__header-wrapper tr')
    //   this.sortable = Sortable.create(wrapperTr, {
    //     animation: 180,
    //     delay: 0,
    //     onEnd: evt => {
    //       const oldItem = this.dropCol[evt.oldIndex]
    //       this.dropCol.splice(evt.oldIndex, 1)
    //       this.dropCol.splice(evt.newIndex, 0, oldItem)
    //     }
    //   })
    // }
  }
}
</script>
<style scoped>
/* .item {
  padding: 6px;
  background-color: #fdfdfd;
  border: solid 1px #eee;
  margin-bottom: 10px;
   cursor: move;
}

.item:hover {
  background-color: #f1f1f1;
  cursor: move;
} */

.chosen {
  border: solid 2px #3089dc !important;
}
/* ::v-deep .el-table tr {
  cursor: move;
} */
::v-deep .el-dialog {
  min-width: 360px !important;
}
.flowForms {
  position: relative;
}
.flowForms .iconadd {
  position: absolute;
  right: 0;
  top: 0;
  cursor: pointer;
}
.flowForms ::v-deep .el-select.el-select--mini,
.flowForms ::v-deep .el-form--inline .el-form-item {
  width: 100%;
}
.flowForms ::v-deep .el-form-item--mini .el-form-item__content {
  width: 63%;
}
</style>
